package cn.itcast.utils;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.system.Module;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SerializableObject {
        public byte[] serializeObject(Object obj) {
            ByteArrayOutputStream byteOutputStream = null;
            ObjectOutputStream objectOutputStream = null;

            try{
                byteOutputStream = new ByteArrayOutputStream();
                objectOutputStream = new ObjectOutputStream(byteOutputStream);

                objectOutputStream.writeObject(obj);
                objectOutputStream.flush();

                return byteOutputStream.toByteArray();
            }catch(Exception e){
                e.printStackTrace();
            } finally {
                if(null != objectOutputStream){
                    try{
                        objectOutputStream.close();
                        byteOutputStream.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }

            return null;
        }
        public  Object deserializeObject(byte[] bytes) {
            ByteArrayInputStream byteInputStream = null;
            ObjectInputStream objectInputStream = null;

            try{
                byteInputStream = new ByteArrayInputStream(bytes);
                objectInputStream = new ObjectInputStream(byteInputStream);

                return objectInputStream.readObject();

            }catch(Exception e){
                e.printStackTrace();
            }finally {
                if(null != objectInputStream){
                    try{
                        objectInputStream.close();
                        byteInputStream.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

    public static void main(String[] args) {
        SerializableObject serializableObject = new SerializableObject();
        List<Module> moduleArrayList = new ArrayList<>();

        for (int i = 0; i < 3; i++) {
            Module contract = new Module();
            contract.setId(""+i);
            moduleArrayList.add(contract);
        }
        byte[] bytes = serializableObject.serializeObject(moduleArrayList);
        System.out.println(bytes);
        List<Module> moduleArrayList1 = (List<Module>) serializableObject.deserializeObject(bytes);
        for (Module module : moduleArrayList1) {
            System.out.println(module.getId());
        }
    }
}

